home *** CD-ROM | disk | FTP | other *** search
- Path: ts17-13.tor.InfoRamp.Net!pitchl
- From: pitchl@tdbank.ca (Lew Pitcher)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sat, 20 Jan 1996 02:59:02
- Organization: Toronto Dominion Bank
- Message-ID: <pitchl.43.0002FC00@tdbank.ca>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: ts17-13.tor.inforamp.net
- X-Newsreader: Trumpet for Windows [Version 1.0 Rev A]
-
- In article <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> Bill Simpson <wsimpson@uwinnipeg.ca> writes:
- >From: Bill Simpson <wsimpson@uwinnipeg.ca>
- >Subject: quick decision: is n a power of 2?
- >Date: Fri, 19 Jan 1996 12:00:01 -0600
-
- >Is there a fast way to decide whether a number n is a power of 2?
-
- ..snip..
-
- >Since I am dealing with unsigned long ints, I guess I can just store all
- >31 powers of 2 in a table and compare to n. Though I don't know a fast
- >algorithm to compare a number to 31 numbers in an array.
-
- >Perhaps there is a tricky nonportable way to see if I have power-of-2 by
- >looking at bits? (That is fine for this application)
- How about a tricky portable way...
- For unsigned integers, a value that is a power of two will consist of only one
- '1' bit and a lot of '0' bits. The following table illustrates this
- observation. 2^0 == 1 == b'00001'
- 2^1 == 2 == b'00010'
- 2^2 == 4 == b'00100'
- 2^3 == 8 == b'01000'
- etcetera
-
- /* is_power_of_2() returns 0 if num is not a power of 2, and 1 if it is */
- int is_power_of_2(num)
- unsigned long num;
- {
- int bitcount; /* assume no more than MAX_INT bits in longint*/
-
- for (bitcount = 0; num; num >>= 1)
- if (n&1) ++ bitcount;
- return (bitcount == 1) ? 1 : 0;
- }
-
- >Thanks very much for any help.
-
- You're welcome
-
- >Bill Simpson
-
-
- Lew Pitcher | "I'm a little source code
- Toronto Dominion Bank | Short and Stout
- ======================= | Here is my Input,
- Enzo Matrix - Reboot | And here is my out"
-